package sorter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Observable;
import java.util.Observer;

public class ListJoiner implements Observer {

	private int lastThreadNumber = -1;
	private ArrayList<Comparable> resultArray = new ArrayList<Comparable>();
	private int joinedThreads = -1;
	private Comparable[][] lists;


	public ListJoiner(int aantalLists) {
		lists = new Comparable[aantalLists][];
	}

	public ListJoiner getListJoiner() {
		return this;
	}

	public int getNextThreadNumber() {
		lastThreadNumber = lastThreadNumber + 1;
		return lastThreadNumber;
	}

	public void join() {
		try {
			for (Comparable[] lst : lists) {			
			Collections.addAll(resultArray, lst);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	public void createNewLists(Comparable[] anArray, int threadNumber){
		lists[threadNumber] = anArray;
		joinedThreads = joinedThreads + 1;
	}

	public ArrayList<Comparable> getResultArray(){
		return resultArray;
	}
	
	public void printJoinedList() {			
		Iterator<Comparable> it = resultArray.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
	}

	@Override
	public void update(Observable mySorterThread, Object list) {		
		int tnumber = ((SorterThread) mySorterThread).getThreadNumber();
		createNewLists((Comparable[])list,tnumber);
        if(joinedThreads == lastThreadNumber)
        {
        	//System.out.println("" + System.nanoTime());
        	join();
            printJoinedList();
        }

	}

}
